package com.blue.base.web.util;

import com.blue.base.common.bean.resp.JsonResult;
import com.blue.base.common.exception.BaseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.function.Supplier;

/**
 * 异常处理分层工具类：保证自定义异常抛出，又避免系统500类型异常直接返回给前端
 *
 * @author liulei
 * @version 1.0
 */
public class WebResponseUtil {

    private static final Logger log = LoggerFactory.getLogger(WebResponseUtil.class);

    /**
     * controller层带异常统一返回
     *
     * @param executor         执行器-service返回resp包装的结果[带自定义异常抛出]
     * @param errorDescription 出现程序错误500侯，接口的整体错误描述
     * @return resp
     */
    public static <T> JsonResult<T> returnWithException(Supplier<JsonResult<T>> executor, String errorDescription) {
        JsonResult<T> result;
        try {
            result = executor.get();
        } catch (BaseException e) {
            log.error("业务异常", e);
            throw e;
        } catch (Exception e) {
            log.error("系统异常", e);
            throw new BaseException(500, errorDescription);
        }
        return result;
    }

    /**
     * controller层带异常统一返回
     *
     * @param executor         执行器-service返回简单结果[带自定义异常抛出]
     * @param errorDescription 出现程序错误500侯，接口的整体错误描述
     * @return resp
     */
    public static <T> JsonResult<T> directReturnWithException(Supplier<T> executor, String errorDescription) {
        JsonResult<T> result = JsonResult.ok(null);
        try {
            result.setData(executor.get());
        } catch (BaseException e) {
            log.error("业务异常", e);
            throw e;
        } catch (Exception e) {
            log.error("系统异常", e);
            throw new BaseException(500, errorDescription);
        }
        return result;
    }
}
